//
// Created by steven on 2017/2/23.
// Copyright (c) 2017 steven. All rights reserved.
//

#import "GMDebtorListViewController.h"
#import <MMDrawerController/UIViewController+MMDrawerController.h>
#import <MMDrawerController/MMDrawerBarButtonItem.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "GMAddClientViewController.h"
#import "GMClientDetailViewController.h"
#import "GMDebtorDataController.h"
#import "GMDebtorModel.h"
#import "GMPinAnnotationView.h"
#import "GMPointAnnotation.h"

enum {
    AnnotationViewControllerAnnotationTypeRed = 0,
    AnnotationViewControllerAnnotationTypeGreen,
    AnnotationViewControllerAnnotationTypePurple
};

@interface GMDebtorListViewController()<MAMapViewDelegate>

@property (nonatomic, strong)MAMapView *mapView;
@property (nonatomic, strong) NSMutableArray<GMPointAnnotation *> *annotations;
@property (nonatomic, strong)GMDebtorDataController *debtorDataController;
@end

@implementation GMDebtorListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.debtorDataController = [[GMDebtorDataController alloc] init];

    [self setupMainView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    MMDrawerBarButtonItem * leftDrawerButton = [[MMDrawerBarButtonItem alloc] initWithTarget:self action:@selector(leftDrawerButtonPressed)];
    [self.navigationItem setLeftBarButtonItem:leftDrawerButton animated:YES];

    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加客户" style:UIBarButtonItemStylePlain
                                                                       target:self action:@selector(rightBarButtonItemPressed)];
    [self.navigationItem setRightBarButtonItem:rightButtonItem animated:YES];

    //设置打开抽屉模式
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];

    // load debtors locations
    [self loadDebtors];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    //设置打开抽屉模式
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
}

- (void)loadDebtors {
    [self.debtorDataController requestDebtorsWithParams:nil callback:^(NSString *error) {
        if (error == nil) {
            [self renderSuccessView];
        } else {
            [self showAlertMessage:error];
        }
    }];
}


- (void)renderSuccessView {
    NSArray<GMDebtorModel *>*debtors = self.debtorDataController.debtors;
    // title
    if (debtors.count > 0) {
        self.navigationItem.title = [NSString stringWithFormat:@"客户守卫(%ld人)", (long)debtors.count];
    }
    // Remove all annotations first.
    [self.mapView removeAnnotations:self.annotations];

    // Add new annoations.
    self.annotations = [NSMutableArray array];

    [debtors enumerateObjectsUsingBlock:^(GMDebtorModel *obj, NSUInteger idx, BOOL *stop) {
        GMPointAnnotation *annotation = [[GMPointAnnotation alloc] init];
        CLLocationCoordinate2D coordinate = {obj.lat, obj.log};
        annotation.coordinate = coordinate;
        annotation.customerId = [NSString stringWithFormat:@"%ld", (long)obj.id];
        [self.annotations addObject:annotation];
    }];


    [self.mapView addAnnotations:self.annotations];
    [self.mapView showAnnotations:self.annotations edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
    if (self.annotations.count == 1) {
        [self.mapView setZoomLevel:MAP_ZOOM_LEVEL animated:YES];
        [self.mapView setCenterCoordinate:[self.annotations lastObject].coordinate];
    }
}

#pragma mark - setup main view
- (void)setupMainView {
    self.navigationItem.title = @"客户守卫";

    [self.view addSubview:self.mapView];
    [self.mapView autoPinEdgesToSuperviewEdges];
}

#pragma mark - leftDrawerButtonPress
- (void)leftDrawerButtonPressed {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

#pragma mark - rightBarButtonItemPressed
- (void)rightBarButtonItemPressed {
    GMAddClientViewController *addClientViewController = [[GMAddClientViewController alloc] init];
    [self.navigationController pushViewController:addClientViewController animated:YES];
}

#pragma mark - map
- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] init];
        _mapView.delegate = self;
    }

    return _mapView;
}

#pragma mark - Map Delegate

/*!
 @brief 根据anntation生成对应的View
 @param mapView 地图View
 @param annotation 指定的标注
 @return 生成的标注View
 */
- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[GMPointAnnotation class]])
    {
        GMPointAnnotation *annotationPoint = (GMPointAnnotation *)annotation;

        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        GMPinAnnotationView *annotationView = (GMPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[GMPinAnnotationView alloc] initWithAnnotation:annotationPoint reuseIdentifier:pointReuseIndetifier];
            annotationView.customerId = annotationPoint.customerId;
        }
        
        annotationView.canShowCallout               = NO;
//        annotationView.animatesDrop                 = YES;
//        annotationView.draggable                    = YES;
//        annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//        annotationView.pinColor                     = 0;
        annotationView.image = [UIImage imageNamed:@"client-guard-icon"];

        return annotationView;
    }

    return nil;
}

/*!
 @brief 当mapView新添加annotation views时调用此接口
 @param mapView 地图View
 @param views 新添加的annotation views
 */
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    
}

/*!
 @brief 当选中一个annotation views时调用此接口
 @param mapView 地图View
 @param views 选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {

    GMPinAnnotationView *annotationView = (GMPinAnnotationView *)view;
    NSLog(@"customerId: %@", annotationView.customerId);

    GMClientDetailViewController *clientDetailViewController = [[GMClientDetailViewController alloc] init];
    clientDetailViewController.debtorId = annotationView.customerId;
    [self.navigationController pushViewController:clientDetailViewController animated:YES];
}

/*!
 @brief 当取消选中一个annotation views时调用此接口
 @param mapView 地图View
 @param views 取消选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view {
    
}

/*!
 @brief 标注view的accessory view(必须继承自UIControl)被点击时调用此接口
 @param mapView 地图View
 @param annotationView callout所属的标注view
 @param control 对应的control
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    
}

/**
 *  标注view的calloutview整体点击时调用此接口
 *
 *  @param mapView 地图的view
 *  @param view calloutView所属的annotationView
 */
- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view {
    
}

/*!
 @brief 拖动annotation view时view的状态变化，ios3.2以后支持
 @param mapView 地图View
 @param view annotation view
 @param newState 新状态
 @param oldState 旧状态
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view didChangeDragState:(MAAnnotationViewDragState)newState fromOldState:(MAAnnotationViewDragState)oldState {
    
}

@end
